package com.sxfq.loansupermarket.backsystem.modular.marketing.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.sxfq.loansupermarket.backsystem.common.constant.factory.PageFactory;
import com.sxfq.loansupermarket.backsystem.common.controller.BaseController;
import com.sxfq.loansupermarket.backsystem.common.persistence.model.User;
import com.sxfq.loansupermarket.backsystem.core.log.LogManager;
import com.sxfq.loansupermarket.backsystem.core.log.factory.LogTaskFactory;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.support.DateTimeKit;
import com.sxfq.loansupermarket.backsystem.core.support.HttpKit;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.ApprovalAuditInfo;
import com.sxfq.loansupermarket.backsystem.modular.base.SqlMapper;
import com.sxfq.loansupermarket.backsystem.modular.marketing.entity.ApprovalProcessInfo;
import com.sxfq.loansupermarket.backsystem.modular.marketing.entity.ReservationsInfo;
import com.sxfq.loansupermarket.backsystem.modular.marketing.entity.SearchApprovalProcessInfo;
import com.sxfq.loansupermarket.backsystem.modular.marketing.service.IReservationsService;
import com.sxfq.loansupermarket.backsystem.modular.marketing.service.ISecondDevelopmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 二次开发审核信息
 *
 * @author
 * @Date
 */
@Controller
@RequestMapping("/reservations_second")
public class SecondDevelopmentController extends BaseController {
    @Autowired
    ISecondDevelopmentService service;

    @Autowired
    IReservationsService reservationsService;

    @Autowired
    private SqlMapper sqlMapper;

    private String PREFIX = "/marketing/reservations/";

    /**
     * 跳转到审核界面
     */
    @RequestMapping("")
    public String reservations(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        model.addAttribute("outpatientManagementList", ShiroKit.getSessionAttr("outpatientManagementList"));
        model.addAttribute("channelAuditLevel", ShiroKit.getUser().getChannelAuditLevel());
        return PREFIX + "second_development.html";
    }

    /**
     * 审核管理列表
     */
    @RequestMapping("/list")
    @ResponseBody
    public Object secondDevelopmentList(SearchApprovalProcessInfo info, HttpServletRequest request) {
        Page<ApprovalProcessInfo> page = new PageFactory<ApprovalProcessInfo>().defaultPage();
        try {
            List<ApprovalProcessInfo> list = new ArrayList<ApprovalProcessInfo>();
            if("exe".equals(info.getExeValue())){
                info.setStartIndex(page.getSize()*(page.getCurrent()-1));
                info.setLimitIndex(page.getSize());
                page.setCurrent(0);
                list = service.selectPageListByGetMap(page, info);
                if (list.size() == 0) {
                    info.setStartIndex(0);
                    list = service.selectPageListByGetMap(page, info);
                }
                page.setTotal(service.getQueryPagesGetMapCount(page, info));
                page.setRecords(list);
            }else if("tri".equals(info.getExeValue())){
                info.setStartIndex(page.getSize()*(page.getCurrent()-1));
                info.setLimitIndex(page.getSize());
                page.setCurrent(0);
                list = service.selectPageListByGetMapYi(page, info);
                if (list.size() == 0) {
                    info.setStartIndex(0);
                    list = service.selectPageListByGetMapYi(page, info);
                }
                page.setTotal(service.getQueryPagesGetMapCountYi(page, info));
                page.setRecords(list);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.packForBT(page);
    }

    /**
     * 二次开发审核跳转
     */
    @RequestMapping(value = "/reservations_modify/{ids}")
    public String reservations_modify(Model model, @PathVariable String ids) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        try {
            String id = ids.split(",")[0];
            String reservationsId = ids.split(",")[1];
            String sql = "select id as id,customer_name as customerName,customer_phone as customerPhone,remarks as remarks,name as name,follower as follower," +
                    "belonger as belonger,one_channel as oneChannel,two_channel as twoChannel,channel_audit_level as channelAuditLevel," +
                    "thr_channel as thrChannel,left(operation_time,19) as operationTime,submitter as submitter," +
                    "(CASE result " +
                    "  WHEN 1 THEN " +
                    "  '审核通过' " +
                    "  WHEN 2 THEN " +
                    "  '审核未通过' " +
                    "  ELSE " +
                    "  '审核进行中' " +
                    "  END " +
                    " ) as result from reservations_second_development where id = '" + id + "' limit 1";
            ApprovalProcessInfo info = sqlMapper.selectOne(sql,ApprovalProcessInfo.class);
            model.addAttribute("info", info);
            model.addAttribute("id", id);
            model.addAttribute("reservationsId", reservationsId);
            return PREFIX + "second_modify_development.html";
        } catch (Exception e) {
            return "/errorClose.html";
        }
    }

    /**
     * 二次开发审核跳转
     */
    @RequestMapping(value = "/reservations_modifys/{ids}")
    public String reservations_modifys(Model model, @PathVariable String ids) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        try {
            String id = ids.split(",")[0];
            String reservationsId = ids.split(",")[1];
            String sql = "select id as id,customer_name as customerName,customer_phone as customerPhone,remarks as remarks,name as name,follower as follower," +
                    "belonger as belonger,one_channel as oneChannel,two_channel as twoChannel,channel_audit_level as channelAuditLevel,examine_remarks as examineRemarks," +
                    "thr_channel as thrChannel,left(operation_time,19) as operationTime,submitter as submitter," +
                    "(CASE result " +
                    "  WHEN 1 THEN " +
                    "  '审核通过' " +
                    "  WHEN 2 THEN " +
                    "  '审核未通过' " +
                    "  ELSE " +
                    "  '审核进行中' " +
                    "  END " +
                    " ) as result from reservations_second_development where id = '" + id + "' limit 1";
            ApprovalProcessInfo info = sqlMapper.selectOne(sql,ApprovalProcessInfo.class);
            model.addAttribute("info", info);
            model.addAttribute("id", id);
            model.addAttribute("reservationsId", reservationsId);
            return PREFIX + "second_modify_developments.html";
        } catch (Exception e) {
            return "/errorClose.html";
        }
    }

    /**
     * 二次开发审核同意提交
     */
    @RequestMapping(value = "/agree", method = RequestMethod.POST)
    @ResponseBody
    public int agree(String examineRemarks, String id,String  reservationsId) throws Exception {
        String sql = "update reservations_second_development a set a.result=1,a.examine_remarks='"+examineRemarks+"',a.time='"+DateTimeKit.now()+"',a.reviewer='"+ShiroKit.getUser().getAccount()+"' where a.id='"+id+"'";
        sqlMapper.update(sql);
        ReservationsInfo reservationsInfo = reservationsService.selectOneById2(reservationsId);
        ReservationsInfo info = reservationsService.selectOneById(reservationsId);
        if(reservationsInfo !=null){
            String updateSql ="update reservations_info a set a.one_channel='二次开发',a.two_channel='二次开发',a.thr_channel='二次开发',a.one_medium='二次开发',a.two_medium='二次开发',a.thr_medium='二次开发' where id='"+reservationsId+"';";
            sqlMapper.update(updateSql);
        }
        if(info !=null){
            String updateSqlsc ="update reservations_infosc a set a.one_channel='二次开发',a.two_channel='二次开发',a.thr_channel='二次开发',a.one_medium='二次开发',a.two_medium='二次开发',a.thr_medium='二次开发' where id='"+reservationsId+"';";
            sqlMapper.update(updateSqlsc);
        }
        return 1;
    }

    /**
     * 二次开发审核拒绝提交
     */
    @RequestMapping(value = "/refuse", method = RequestMethod.POST)
    @ResponseBody
    public int refuse(String examineRemarks, String id) throws Exception {
        String sql = "update reservations_second_development a set a.result=2,a.examine_remarks='"+examineRemarks+"',a.time='"+DateTimeKit.now()+"',a.reviewer='"+ShiroKit.getUser().getAccount()+"' where a.id='"+id+"'";
        sqlMapper.update(sql);
        return 1;
    }
}